<?php

namespace App\Models;


class ServiceCharge extends BaseModel
{
    protected $table = "service_charge";

    protected $rules = [
        'order_sn' => 'required',
        'admin_id' => 'required',
        'shop_id' => 'required',
        'service_id' => 'required',
        'order_amount' => ['required', 'numeric', 'regex:/^([1-9]\d*(\.\d*[1-9])?)|(0\.\d*[1-9])/'],
    ];

    protected $message = [
        'order_sn.required' => '订单号获取失败',
        'admin_id.required' => '商户ID获取失败',
        'shop_id.required' => '店铺ID获取失败',
        'service_id.required' => '服务套餐ID获取失败',
        'order_amount.required' => '订单总价格获取失败',
        'order_amount.numeric' => '订单总价格必须是纯数字',
        'order_amount.regex' => '订单总价格不能小于0',
    ];

    public function service()
    {
        return $this->belongsTo('App\Models\Service', 'service_id', 'id');
    }

    public function shop()
    {
        return $this->belongsTo('App\Models\Shop', 'shop_id', 'id');
    }

    public function getRecord($shopId = 0)
    {
        $where['admin_id'] = plat_admin_id();
        if (is_administrator()) {
            $where = [];
        }
        if ($shopId) {
            $where['shop_id'] = $shopId;
        }
        $keyword = request('keyword');
        $start = request('time-start');
        $end = request('time-end');
        $keyword && $where['order_sn'] = $keyword;
        if ($start && !$end) {
            $timeArea = [strtotime($start), strtotime($start) + 86399];
            sort($timeArea);
            $where['addtime'] = ['between', $timeArea];
        }
        if ($end && !$start) {
            $timeArea = [strtotime($end), strtotime($end) + 86399];
            sort($timeArea);
            $where['addtime'] = ['between', $timeArea];
        }
        if ($start && $end) {
            $timeArea = [strtotime($start), strtotime($end)];
            sort($timeArea);
            $timeArea[1] += 86399;
            $where['addtime'] = ['between', $timeArea];
        }
        $serviceFields = 'id,name,time,base_price';
        $shopFields = 'id,shop_name';
        $rows = $this->_getJoinTwoPageList('service', 'shop', $where, '*', ['id' => 'desc'], 10, 5, $serviceFields, [], $shopFields);
        $txtStr['status'] = [10 => '未支付', 20 => '已支付'];
        $rows['data'] = int_to_string($rows['data'], $txtStr);
        return $rows;
    }

    public function getBaseServiceChargeByAid($adminId)
    {
        //查询商户基础服务费是否需要续费，如果未续费则提示先续费，否则店铺无法续费
        $where['admin_id'] = $adminId;
        $where['category'] = 1;
        $where['status'] = 20;
        $order = $this->_getList($where, 'id,time,payment_time,end_time', ['id' => 'desc'])->toArray();
        if (!$order) {
            $this->error = '请先续费基础服务费';
            return false;
        }
        $now = strtotime(date('Y-m-d'));
        if ($order[0] && ($order[0]['end_time'] < $now)) {
            $this->error = '请先续费基础服务费';
        }
        return $order[0];
    }


    public function addOrder($serviceInfo, $adminId, $shopId = 0)
    {
        if (!($serviceInfo && $adminId)) {
            $this->error = '非法操作';
            return false;
        }
        $data['admin_id'] = $adminId;
        $data['shop_id'] = $shopId;
        $data['service_id'] = $serviceInfo['id'];
        $data['time'] = $serviceInfo['time'];
        $data['order_sn'] = makeOrderSn($adminId);
        $data['category'] = $shopId ? 0 : 1;
        $data['type'] = request('type', 0);
        $data['addtime'] = time();
        if ($data['category'] && $adminId) {
            $data['order_amount'] = $serviceInfo['base_price'];
        }
        if (!$data['category'] && $shopId) {
            $shop = new Shop();
            $shopInfo = $shop->_redisGetOneBySid($shopId);
            if (!$shopInfo) {
                $this->error = '非法操作';
                return false;
            }
            $data['order_amount'] = $shopInfo['service_price'];
            if ($data['order_amount'] < 1 && is_numeric($serviceInfo['shop_price'])) {
                $data['order_amount'] = $serviceInfo['shop_price'];
            }
            if ($serviceInfo['data'] && $serviceInfo['money'] < 1 && ($shopInfo['service_price'] < 1)) {
                $num = $shop->_count(['admin_id' => $adminId]);
                if (!$num) {
                    $this->error = '商户没有开店';
                    return false;
                }
                $money = 0;
                foreach ($serviceInfo['data'] as $v) {
                    if (!is_array($v[0])) {
                        $this->error = '套餐数据不合法';
                        return false;
                    }
                    $min = $v[0][0];
                    $max = $v[0][1];
                    if ($num >= $min && $num <= $max) {
                        $money = $v[1];
                    }
                }
                if (!$money) {
                    if ($num == 1) {
                        $money = $serviceInfo['data'][0][1];
                    } else {
                        $money = $serviceInfo['data'][count($serviceInfo['data'])][1];
                    }
                }
                if (!$money) {
                    $this->error = '计算订单金额错误';
                    return false;
                }
                $data['order_amount'] = $money;
            }
        }
        if (!$this->_validate($data)) {
            return false;
        }
        $res = $this->_save($data);
        if (!$res) {
            $this->error = '生成订单失败！';
            return false;
        }
        $data['id'] = $res;
        $data['service_name'] = $serviceInfo['name'];
        $data['service_time'] = $serviceInfo['time'];
        return $data;
    }


    public function dealOrder($order_sn)
    {
        //修改数据库订单状态
        $order = $this->_getOne(['order_sn' => $order_sn]);
        if (!$order) {
            $this->error = '订单号不存在';
            return false;
        }
        $order = $order->toArray();
        if ($order['type'] == 0 && $order['status'] == 10) {
            $now = time();
            $data['id'] = $order['id'];
            $data['status'] = 20;
            $data['payment_time'] = $now;
            $this->_start();
            try {
                $service = new Service();
                $serviceInfo = $service->getInfo($order['admin_id']);
                if ($serviceInfo) {
                    if ($order['category']) {
                        $chargeInfo = $this->getBaseServiceChargeByAid($order['admin_id']);
                        $time = $now;
                        if ($chargeInfo) {
                            $time = $chargeInfo['end_time'] > $now ? $chargeInfo['end_time'] : $now;
                        }
                        $data['end_time'] = strtotime(date('Y-m-d', strtotime("+{$serviceInfo['time']}year", $time))) + 86399;
                    }
                    //单店或者分店续费
                    if (!$order['category']) {
                        $shop = new Shop();
                        $shopInfo = $shop->_redisGetOneBySid($order['shop_id']);
                        if ($shopInfo) {
                            if ($shopInfo['service_price'] < 1) {
                                $shopData['service_price'] = $order['order_amount'];
                            }
                            $shopData['status'] = 1;
                            $shopData['start_time'] = $now;
                            $time = $shopInfo['end_time'] > $now ? $shopInfo['end_time'] : $now;
                            $shopData['end_time'] = strtotime(date('Y-m-d', strtotime("+{$serviceInfo['time']}year", $time))) + 86399;
                            $data['end_time'] = $shopData['end_time'];
                            $a = $shop->_update(['id' => $shopInfo['id']], $shopData);
                            if (!$a) {
                                $this->error = '更新店铺状态失败！';
                                return false;
                            }
                            $shop->_redisGenerate($order['shop_id']);
                        }
                    }
                }
                $a = $this->_save($data);
                if (!$a) {
                    $this->error = '更新续费订单状态失败！';
                    return false;
                }
                $this->_commit();
                return true;
            } catch (\Exception $e) {
                $this->_rollBack();
                if ($this->error == '') {
                    $this->error = '更新续费订单状态失败！';
                }
                return false;
            }
        }
    }

    //删除未付款线上续费订单
    public function clear()
    {
        $where['type'] = 0;
        $where['status'] = 10;
        $this->_del($where);
    }


}
